package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.iot.IotMsgNotifyData;
import com.zzyl.nursing.dto.DeviceReqDto;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author 张张张
 * @date 2025-09-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceReqDto deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }



    @Autowired
    private IDeviceService deviceService;
    /**
     * 批量保存数据
     * @param dto
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData dto) {
        //1.解析上报的数据 已经做过了
        //2.通过设备id查询设备
        //2.1先获取设备id
        String deviceId = dto.getHeader().getDeviceId();
        //2.2根据id查询设备
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, deviceId)
                .one();
        if(device == null){
            return;
        }

        List<DeviceData> list = new ArrayList<>();
        //只要四个字段没有 需要补充 查询 function_id acccess_location data_value alarm_time
        Map<String, Object> properties = dto.getBody().getServices().get(0).getProperties();
        String eventTime = dto.getBody().getServices().get(0).getEventTime();

        // 定义时间格式器，用于解析字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssZ");

        // 处理可能的Z结尾（UTC标识），替换为+0000便于解析
        String adjustedTimeStr = eventTime.replace("Z", "+0000");

        // 先解析为LocalDateTime，再关联UTC时区转换为Instant
        LocalDateTime utcLocalDateTime = LocalDateTime.parse(adjustedTimeStr, formatter);
        Instant instant = utcLocalDateTime.toInstant(ZoneOffset.UTC);

        // 转换为东八区(Asia/Shanghai)的LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));


        properties.forEach((k,v)->{
            DeviceData deviceData = new DeviceData();
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setIotId(deviceId);
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setFunctionId(k);
            deviceData.setAccessLocation(device.getRemark());
            deviceData.setLocationType(device.getLocationType());
            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            deviceData.setDeviceDescription(device.getDeviceDescription());
            deviceData.setDataValue(v+"");
            deviceData.setAlarmTime(localDateTime);
            list.add(deviceData);
        });


        //3.保存数据
        this.saveBatch(list);



        //day13需要的是为了展示只能床位的
        //存储到redis中  1.数据类型  2.key的名字 这里因为要区分是哪个设备(烟感或者睡眠检测带或者手表)所以用iotId去区分
        //大key:设为固定值
        redisTemplate.opsForHash().put(CacheConstants.DEVICE_LAST_DATA,deviceId, JSONUtil.toJsonStr(list));
         //此处也可以用String结构来存储
        //如果用string结构
        //redisTemplate.opsForValue().set(CacheConstants.DEVICE_LAST_DATA+":"+deviceId,JSONUtil.toJsonStr(list));


    }
}
